package com.yonyou.cyxdms.sysAuth.service.service.auth;


import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.http.RestHttpUtil;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 定义GMMC 的用户认证信息
 *
 * @author: zhangxianchao
 * @since: 2018/9/22 0022
 * @updateDate:
 * @updateRemark:
 * @version:1.0 Copyright: Copyright (c) 2018
 */
@Service
public class ExternalUserAuthServiceImpl implements UserAuthService {

    // 日志对象
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Qualifier("restTemplateNoLb")
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RedisClient redisClient;

    /**
     * 根据主应用的用户信息获取自己应用的用户信息
     *
     * @param token 主应用的用户信息
     * @return org.springframework.http.ResponseEntity
     * @author zhangxianchao
     * @since 2018/9/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public LoginInfoDto getAppUserInfo(String appId, String token, String url, String userAgent) {
        logger.debug("appId:{}", appId);
        logger.debug("userAgent:{}", userAgent);
        logger.debug("url:{}", url);
        logger.debug("token:{}", token);

        HttpHeaders header = RestHttpUtil.getHeader();
        header.set(UserAuthConstant.TOKEN_NAME, token);
        header.set(UserAuthConstant.USER_AGENT, userAgent);
        Map<String, Object> params = new HashMap<>();
        params.put(UserAuthConstant.APP_SOURCE_CODE, appId);
        // 根据token 获取用户信息
        String response = RestHttpUtil.get(params, header, restTemplate, url, String.class);

        logger.debug("appId={},远程获取userInfo:{}", appId, response);

        RestResultResponse<LoginInfoDto> responseDto = JSONUtil.jsonToObj(response,
                new TypeReference<RestResultResponse<LoginInfoDto>>() {
                });

        // 请求异常
        if (responseDto.getResultCode() != 200) {
            throw new ServiceBizException("此jwt不合法，无法换取用户信息");
        }

        LoginInfoDto loginInfo = responseDto.getData();
        String userId = loginInfo.getUserId() == null ? null : String.valueOf(loginInfo.getUserId());
        loginInfo.setUuid(appId + loginInfo.getUserId());
        // 子系统认证已经通过，这时候缓存jwt
        String messageFormat = MessageFormat.format(SysAuthCommonConstants.SUB_JWT, appId, userId);
        redisClient.set(messageFormat, token, SysAuthCommonConstants.EXPIRE_TIME_ONE_HOUR);
        logger.debug("子系统认证通过，登陆信息：{}，\n缓存jwt:key-->{},value-->{}", JSONUtil.objectToJson(loginInfo),
                messageFormat, redisClient.get(messageFormat));
        return loginInfo;
    }
}
